// router_utils.dart
import 'package:flutter/material.dart';

/// 基于 Navigator 2.0 的路由管理工具类
class RouterUtils {
  /// 页面路径映射表
  static final Map<String, WidgetBuilder> _routeBuilders = {};
  
  /// 路由代理实例
  static final AppRouterDelegate _routerDelegate = AppRouterDelegate();
  
  /// 路由信息解析器
  static final RouteInformationParser<_RoutePath> _routeInformationParser = 
      AppRouteInformationParser();

  /// 初始化路由配置
  static void initRoutes(Map<String, WidgetBuilder> routes) {
    _routeBuilders.clear();
    _routeBuilders.addAll(routes);
  }

  /// 获取路由器委托
  static RouterDelegate<Object> get routerDelegate => _routerDelegate;

  /// 获取路由信息解析器
  static RouteInformationParser<Object> get routeInformationParser => 
      _routeInformationParser;

  /// 导航到指定页面
  static void push(BuildContext context, String path, {Object? arguments}) {
    _routerDelegate.push(path, arguments: arguments);
  }

  /// 返回上一页
  static bool pop<T extends Object?>(BuildContext context, [T? result]) {
    return _routerDelegate.pop(result);
  }

  /// 返回到指定页面
  static void popUntil(BuildContext context, String path) {
    _routerDelegate.popUntil(path);
  }

  /// 替换当前页面
  static void replace(BuildContext context, String path, {Object? arguments}) {
    _routerDelegate.replace(path, arguments: arguments);
  }

  /// 清空路由栈并导航到新页面
  static void pushAndRemoveUntil(BuildContext context, String path, 
      {Object? arguments}) {
    _routerDelegate.pushAndRemoveUntil(path, arguments: arguments);
  }

  /// 获取当前路由路径
  static String? get currentPath => _routerDelegate.currentPath;

  /// 获取路由栈大小
  static int get stackSize => _routerDelegate.stack.length;

  /// 检查是否可以返回
  static bool canPop() => _routerDelegate.canPop();
}

/// 路由路径数据类
class _RoutePath {
  final String location;
  final Object? arguments;

  _RoutePath(this.location, this.arguments);
}

/// 自定义路由信息解析器
class AppRouteInformationParser extends RouteInformationParser<_RoutePath> {
  @override
  Future<_RoutePath> parseRouteInformation(RouteInformation routeInformation) async {
    return _RoutePath(routeInformation.location ?? '/', null);
  }

  @override
  RouteInformation restoreRouteInformation(_RoutePath configuration) {
    return RouteInformation(location: configuration.location);
  }
}

/// 应用路由委托
class AppRouterDelegate extends RouterDelegate<_RoutePath>
    with ChangeNotifier, PopNavigatorRouterDelegateMixin<_RoutePath> {
  final List<Page> _pages = [];
  final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();

  /// 当前路由栈
  List<Page> get stack => List.unmodifiable(_pages);

  /// 当前路径
  String? get currentPath {
    if (_pages.isEmpty) return null;
    final page = _pages.last;
    if (page is MaterialPage) {
      return page.name;
    }
    return null;
  }

  @override
  GlobalKey<NavigatorState>? get navigatorKey => this._navigatorKey;

  @override
  Widget build(BuildContext context) {
    return Navigator(
      key: navigatorKey,
      pages: List.of(_pages),
      onPopPage: (route, result) {
        if (!route.didPop(result)) {
          return false;
        }
        
        // 处理页面弹出逻辑
        if (_pages.isNotEmpty) {
          _pages.removeLast();
          notifyListeners();
        }
        return true;
      },
    );
  }

  /// 推入新页面
  void push(String path, {Object? arguments}) {
    final page = _createPage(path, arguments: arguments);
    if (page != null) {
      _pages.add(page);
      notifyListeners();
    }
  }

  /// 弹出当前页面
  bool pop<T extends Object?>([T? result]) {
    if (_pages.isEmpty) return false;
    
    final lastPage = _pages.last;
    final route = ModalRoute.of(navigatorKey!.currentContext!)!;
    
    if (route.isCurrent) {
      route.didPop(result);
      _pages.removeLast();
      notifyListeners();
      return true;
    }
    
    return false;
  }

  /// 弹出页面直到指定路径
  void popUntil(String path) {
    final index = _pages.lastIndexWhere((page) => page.name == path);
    if (index != -1) {
      _pages.removeRange(index + 1, _pages.length);
      notifyListeners();
    }
  }

  /// 替换当前页面
  void replace(String path, {Object? arguments}) {
    if (_pages.isNotEmpty) {
      _pages.removeLast();
    }
    push(path, arguments: arguments);
  }

  /// 推入新页面并移除之前的所有页面
  void pushAndRemoveUntil(String path, {Object? arguments}) {
    _pages.clear();
    push(path, arguments: arguments);
  }

  /// 创建页面
  Page? _createPage(String path, {Object? arguments}) {
    final builder = RouterUtils._routeBuilders[path];
    if (builder == null) {
      // 如果没有找到对应路由，可以返回错误页面或默认页面
      return null;
    }
    
    final widget = builder.call(navigatorKey!.currentContext!);
    return MaterialPage(
      key: ValueKey(path),
      name: path,
      arguments: arguments,
      child: widget,
    );
  }

  /// 检查是否可以弹出页面
  bool canPop() {
    return _pages.length > 1;
  }

  @override
  Future<void> setNewRoutePath(_RoutePath configuration) async {
    // 根据路径配置设置新的路由
    final page = _createPage(configuration.location, 
        arguments: configuration.arguments);
    if (page != null) {
      _pages.clear();
      _pages.add(page);
      notifyListeners();
    }
  }
}
